package com.maserb.monitor.repository.impl;

import com.maserb.monitor.common.IdUtils;
import com.maserb.monitor.database.JdbcTemplateFactory;
import com.maserb.monitor.database.PreparedStatementUtils;
import com.maserb.monitor.entity.AlarmEntity;
import com.maserb.monitor.repository.AlarmRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.Calendar;

@Repository
public class AlarmRepositoryImpl implements AlarmRepository {
    @Autowired
    JdbcTemplateFactory jdbcTemplateFactory;

    @Override
    public void save(AlarmEntity entity, String deviceCode) {
        JdbcTemplate jdbcTemplate = jdbcTemplateFactory.getTemplate(deviceCode);
        String tableName = getTablename(Calendar.getInstance().get(Calendar.YEAR));
        makesureTableExists(jdbcTemplate, tableName);
        entity.setId(IdUtils.generateId());
        String insertSql = "insert into alarm_data(deviceCode,pointCode,status,alarmTime,id) values(?,?,?,?,?)";

        prepareSaveParameters(entity, jdbcTemplate, insertSql);
    }

    private void prepareSaveParameters(AlarmEntity entity, JdbcTemplate jdbcTemplate, String insertSql) {
        jdbcTemplate.update(insertSql, ps ->
        {
            PreparedStatementUtils.setString(ps, 1, entity.getDeviceCode());
            PreparedStatementUtils.setString(ps, 2, entity.getPointCode());
            PreparedStatementUtils.setInt(ps, 3, entity.getStatus().getValue());
            PreparedStatementUtils.setDate(ps, 4, entity.getAlarmTime());
            PreparedStatementUtils.setString(ps, 5, entity.getId());
        });
    }

    private void makesureTableExists(JdbcTemplate jdbcTemplate, String tablename) {
        String existTableSql = "SELECT COUNT(*) FROM information_schema.\n" +
                "TABLES WHERE TABLE_NAME='" + tablename + "'";

        Integer count = jdbcTemplate.queryForObject(existTableSql, new Object[]{}, Integer.class);
        if (count < 1) {
            String createTableSql = getAlarmTableSql(tablename);
            jdbcTemplate.execute(createTableSql);
        }
    }

    private String getAlarmTableSql(String tablename) {
        return "CREATE TABLE `" + tablename + "` (\n" +
                "  `id` char(32) NOT NULL,\n" +
                "  `deviceCode` varchar(255) DEFAULT NULL,\n" +
                "  `pointCode` varchar(255) DEFAULT NULL,\n" +
                "  `status` Integer DEFAULT NULL,\n" +
                "  `alarmTime` datetime DEFAULT NULL,\n" +
                "  PRIMARY KEY (`id`)\n" +
                ") ENGINE=InnoDB DEFAULT CHARSET=utf8;";
    }

    private String getTablename(int year) {
        String tableName = "alarm_data" + year;
        return tableName;
    }
}
